import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let firstOpenTime = ''
export default new Vuex.Store({
	state: {
		socketTask: null, // ws链接
		webSocketPingTimer: null, // 心跳定时器
		webSocketPingTime: 50000, // 心跳的间隔，当前为 50秒,
		serverTimeoutObj:null, // 服务器心跳定时器
		severTimeout:5000,// 服务器超时时间
		webSocketReconnectCount: 0, // 重连次数
		webSocketIsReconnect: true, // 是否重连
		webSocketIsOpen: false,
		sendMsgStatus:false,
		msg: null ,//接收到的信息
		weUserId:'',
		userSource:'SGSMART',
		trfNo:'',
		isFirstReconnetFail:false
	},
	getters: {
		// 获取接收的信息
		socketMsgs: state => {
			return state.msg
		},
    webSocketPingTimer:state => {
      return state.webSocketPingTimer
    },
		weUserId:state=>state.weUserId,
		trfNo:state=>state.trfNo,
		webSocketReconnectCount:state=>state.webSocketReconnectCount,
		socketTask:state=>state.socketTask,
		isFirstReconnetFail:state=>state.isFirstReconnetFail
	},
	mutations: {
		setweUserId(state,val) {
			state.weUserId = val
		},
		settrfNo(state,val) {
			state.trfNo = val
		},
		setWebSocketIsReconnect(state, val) {
			state.webSocketIsReconnect = val
		},
		// setwebSocketReconnectCount(state, val) {
		// 	state.webSocketReconnectCount = val
		// },
		setsocketTask(state, val) {
			state.socketTask = val
		},
		//初始化ws 用户登录后调用
		webSocketInit(state,info) {
			let that = this
			let host = ''
			if (process.env.NODE_ENV === 'development') {
				host = 'test.sgsmart-online.com'
			} else {
				host = window.location.host
			}
			state.socketTask = uni.connectSocket({
				url: `wss://${host}/ws?weUserId=${that.state.weUserId}&userSource=${that.state.userSource}&trfNo=${that.state.trfNo}`,
				success(data) {
					firstOpenTime = new Date()
				},
			});
			// ws连接开启后登录验证
			state.socketTask.onOpen((res) => {
				//开始心跳
				state.webSocketIsOpen = true;
				that.commit('webSocketPing')
				// 注：只有连接正常打开中 ，才能正常收到消息
				state.socketTask.onMessage((res) => {
					that.commit('webSocketPing')
					// state.webSocketReconnectCount += 1;
					if (JSON.parse(res.data)!="ping") {
						state.msg = JSON.parse(res.data)
					}
				});
			});
 
			// 链接开启后登录验证
			state.socketTask.onError((errMsg) => {
				console.log("ws连接异常")
				that.commit('webSocketClose')
			});
 
			// 链接开启后登录验证
			state.socketTask.onClose((errMsg) => {
				console.log("ws连接关闭")
				that.commit('webSocketClose')
			});
		},
		closeWebSocket(state) {
			if (state.socketTask) {
				state.socketTask.close();
			}
			state.webSocketReconnectCount = 0
			state.webSocketIsReconnect = false
			state.webSocketIsOpen = false;
			state.isFirstReconnetFail = false
			// firstOpenTime = null
			this.commit('setsocketTask',null)
		},
		// 断开连接时
		webSocketClose(state) {
			let that = this
			// 修改状态为未连接
			state.webSocketIsOpen = false;
			this.commit('setsocketTask',null)
			// 判断是否重连
			if (!firstOpenTime) {
				firstOpenTime = new Date()
			}
			let time = new Date().getTime() - firstOpenTime.getTime()
			if (state.webSocketIsReconnect && state.webSocketReconnectCount < 4) {
				if (time > 1000) {
					// 第一次直接尝试重连
					that.commit('webSocketReconnect');
					state.isFirstReconnetFail = false
				} else {
					state.isFirstReconnetFail = true
				}
			}
		},
		// 定时心跳
		webSocketPing() {
			let that = this
			that.state.webSocketPingTimer && clearTimeout(that.state.webSocketPingTimer)
			that.state.serverTimeoutObj && clearTimeout(that.state.serverTimeoutObj)
			that.state.webSocketPingTimer = setTimeout(() => {
				if (!that.state.webSocketIsOpen) {
					return false;
				}
				console.log("心跳");
				const payload = 'ping';
				that.commit('webSocketSend', payload);
				that.state.serverTimeoutObj = setTimeout(function() {
					that.commit('closeWebSocket');
				}, that.state.severTimeout);
			}, that.state.webSocketPingTime);
		},
		// WebSocket 重连
		webSocketReconnect(state) {
			let that = this
			if (state.webSocketIsOpen) {
				return false;
			}
			console.log("第"+state.webSocketReconnectCount+"次重连")
			state.webSocketReconnectCount += 1
			// 判断是否到了最大重连次数
			if (state.webSocketReconnectCount >= 2) {
				state.webSocketIsReconnect = false
				this.webSocketWarningText = "重连次数超限";
			  return false;
			}
			// 初始化
			that.commit('webSocketInit');
			// 每过 5 秒尝试一次，检查是否连接成功，直到超过最大重连次数
			let timer = setTimeout(() => {
				that.commit('webSocketReconnect');
				clearTimeout(timer);
			}, 5000);
		},
 
		// 发送ws消息
		webSocketSend(state, payload) {
			let that = this
			if (!that.state.socketTask) return
			that.state.socketTask.send({
				data: JSON.stringify(payload),
				fail: function(res){
					that.state.sendMsgStatus = true
				},
				success: function(res){
					that.state.sendMsgStatus = false
				}
			})
		}
	},
	actions: {
		webSocketInit({commit},info) {
			commit('setweUserId',info.weUserId)
			commit('settrfNo',info.trfNo)
			commit('webSocketInit')
		},
		webSocketSend({commit}, p) {
			commit('webSocketSend', p)
		}
	}
})